﻿@using System.Linq.Dynamic.Core
@using RadzenBlazorDemos.Data
@using RadzenBlazorDemos.Models.Northwind
@using Microsoft.EntityFrameworkCore

@inherits DbContextPage

<RadzenButton Text="Refresh" Click="@(args => grid.Reload())" class="my-3" />

<RadzenDataGrid @ref=grid Data="@orderDetails" Count="@count" LoadData="@LoadData" TItem="OrderDetail" AllowVirtualization="true" Style="height:400px"
                AllowFiltering="true" FilterPopupRenderMode="PopupRenderMode.OnDemand" FilterCaseSensitivity="FilterCaseSensitivity.CaseInsensitive" LogicalFilterOperator="LogicalFilterOperator.Or"
                AllowSorting="true">
    <Columns>
        <RadzenDataGridColumn TItem="OrderDetail" Property="OrderID" Title="OrderID" />
        <RadzenDataGridColumn TItem="OrderDetail" Property="ProductID" Title="ProductID" />
        <RadzenDataGridColumn TItem="OrderDetail" Property="UnitPrice" Title="Unit Price">
            <Template Context="detail">
                @String.Format(new System.Globalization.CultureInfo("en-US"), "{0:C}", detail.UnitPrice)
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="OrderDetail" Property="Quantity" Title="Quantity" />
        <RadzenDataGridColumn TItem="OrderDetail" Property="Discount" Title="Discount">
            <Template Context="detail">
                @String.Format("{0}%", detail.Discount * 100)
            </Template>
        </RadzenDataGridColumn>
    </Columns>
</RadzenDataGrid>

<EventConsole @ref=@console />
@code {
    EventConsole console;
    RadzenDataGrid<OrderDetail> grid;
    int count;
    IEnumerable<OrderDetail> orderDetails;

    void LoadData(LoadDataArgs args)
    {
        console.Log($"Skip: {args.Skip}, Top: {args.Top}");

        var query = dbContext.OrderDetails.AsQueryable();

        if (!string.IsNullOrEmpty(args.Filter))
        {
            query = query.Where(args.Filter);
            count = query.Count();
        }
        else
        {
            count = dbContext.OrderDetails.Count();
        }

        if (!string.IsNullOrEmpty(args.OrderBy))
        {
            query = query.OrderBy(args.OrderBy);
        }

        orderDetails = query.Skip(args.Skip.Value).Take(args.Top.Value).ToList();
    }
}
